# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(ggrepel)
library(ropls)
library(pROC)
library(egg)
library(optparse)
library(tidyverse)

createWhenNoExist <- function(f){
    ! dir.exists(f) && dir.create(f)
}

option_list <- list(
make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

options(digits = 3)

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
select(c("SampleID", "ClassNote"))

head(sampleInfo)

fileName <- "../../03/true_boruta_after.txt"

if(!file.exists(fileName)){
    quit(status = 0)
}

diffNames <- read_tsv(fileName) %>%
  .$Metabolite

print(diffNames)
data <- read_csv(opt$i) %>%
    select(- c("HMDB", "KEGG", "Class")) %>%
    filter(Metabolite %in% diffNames) %>%
    gather("SampleID", "Value", - Metabolite) %>%
    spread(Metabolite, "Value") %>%
    inner_join(sampleInfo, by = c("SampleID"))

data

getRoc <- function(name){
    x <- data[name] %>% unlist()
    y <- data$ClassNote
    rocRs <- roc(y, x, ci = T)
    return(list(name = name, roc = rocRs))
}
rocs <- diffNames %>%
map(getRoc)

aucData <- rocs %>%
    map_dfr(function(rocList){
        rocRs <- rocList$roc
        name <- rocList$name
        auc <- round(rocRs$auc, 3)
        ci <- rocRs$ci
        ci1 <- ci[1]
        ci2 <- ci[3]
        pointData <- coords(rocRs, "best", transpose = FALSE) %>%
            round(3) %>%
            as.data.frame()
        return(data.frame(Metabolite = name, AUC = auc, CI1 = ci1, CI2 = ci2, Thres = pointData$threshold,
        Specificity = pointData$specificity, Sensitivity = pointData$sensitivity))
    }) %>%
    arrange(desc(AUC))

aucData

outFileName <- "Single_Met_ROC.csv"
write.csv(aucData, outFileName, row.names = F)









